package com.ecommerce.product.controller;

import com.ecommerce.product.dto.CategoryCreateRequest;
import com.ecommerce.product.dto.CategoryResponse;
import com.ecommerce.product.dto.CategoryUpdateRequest;
import com.ecommerce.product.service.CategoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;

/**
 * 分类控制器
 */
@RestController
@RequestMapping("/categories")
@RequiredArgsConstructor
public class CategoryController {

    private final CategoryService categoryService;

    /**
     * 获取所有可见分类
     * @return 分类列表
     */
    @GetMapping
    public ResponseEntity<List<CategoryResponse>> getAllCategories() {
        List<CategoryResponse> categories = categoryService.getAllVisibleCategories();
        return ResponseEntity.ok(categories);
    }

    /**
     * 获取所有分类（包括已删除的）
     * @return 分类列表
     */
    @GetMapping("/all")
    public ResponseEntity<List<CategoryResponse>> getAllCategoriesWithDeleted() {
        List<CategoryResponse> categories = categoryService.getAllCategories();
        return ResponseEntity.ok(categories);
    }

    /**
     * 根据ID获取分类
     * @param id 分类ID
     * @return 分类信息
     */
    @GetMapping("/{id}")
    public ResponseEntity<CategoryResponse> getCategoryById(@PathVariable Long id) {
        CategoryResponse category = categoryService.getCategoryById(id);
        return ResponseEntity.ok(category);
    }

    /**
     * 获取指定父分类下的子分类
     * @param parentId 父分类ID（可选）
     * @return 子分类列表
     */
    @GetMapping("/children")
    public ResponseEntity<List<CategoryResponse>> getCategoriesByParentId(@RequestParam(required = false) Long parentId) {
        List<CategoryResponse> categories = categoryService.getCategoriesByParentId(parentId);
        return ResponseEntity.ok(categories);
    }

    /**
     * 创建分类
     * @param request 创建请求
     * @return 创建的分类
     */
    @PostMapping
    public ResponseEntity<CategoryResponse> createCategory(@Valid @RequestBody CategoryCreateRequest request) {
        CategoryResponse category = categoryService.createCategory(request);
        return ResponseEntity.status(HttpStatus.CREATED).body(category);
    }

    /**
     * 更新分类
     * @param id 分类ID
     * @param request 更新请求
     * @return 更新的分类
     */
    @PutMapping("/{id}")
    public ResponseEntity<CategoryResponse> updateCategory(@PathVariable Long id, @Valid @RequestBody CategoryUpdateRequest request) {
        CategoryResponse category = categoryService.updateCategory(id, request);
        return ResponseEntity.ok(category);
    }

    /**
     * 删除分类（逻辑删除）
     * @param id 分类ID
     * @return 无内容
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteCategory(@PathVariable Long id) {
        categoryService.deleteCategory(id);
        return ResponseEntity.noContent().build();
    }
}